<template>
<div>
	<!-- 创意列表 -->
	    <!-- 加载 -->
    <div class="example">
        <a-spin size="large" tip="Loading..." :spinning="spinning" />
    </div>
	<div v-if="spinning ==false">
		<a-card>
			<div :class="advanced ? 'search' : null">
			<a-form layout="horizontal" :form="form" @submit="handleSubmit">
				<div :class="advanced ? null: 'fold'">
				<a-row >
				<a-col :md="8" :sm="24" >
					<a-form-item
					label="创意状态"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-select 
					v-decorator="[
					'status',
					]"
						placeholder="请选择创意状态" :allowClear="true">
						<a-select-option value="CREATIVE_STATUS_DELIVERY_OK">投放中</a-select-option>
						<a-select-option value="CREATIVE_STATUS_NOT_START">未到达投放时间</a-select-option>
						<a-select-option value="CREATIVE_STATUS_NO_SCHEDULE">不在投放时段</a-select-option>
						<a-select-option value="CREATIVE_STATUS_DISABLE">创意暂停</a-select-option>
						<a-select-option value="CREATIVE_STATUS_CAMPAIGN_DISABLE">已被广告组暂停</a-select-option>
						<a-select-option value="CREATIVE_STATUS_CAMPAIGN_EXCEED">广告组超出预算</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AUDIT">新建审核中</a-select-option>
						<a-select-option value="CREATIVE_STATUS_REAUDIT">修改审核中</a-select-option>
						<a-select-option value="CREATIVE_STATUS_DELETE">已删除</a-select-option>
						<a-select-option value="CREATIVE_STATUS_DONE">已完成</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AD_DISABLE">广告计划暂停</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AUDIT_DENY">审核不通过</a-select-option>
						<a-select-option value="CREATIVE_STATUS_BALANCE_EXCEED">账户余额不足</a-select-option>
						<a-select-option value="CREATIVE_STATUS_BUDGET_EXCEED">超出预算</a-select-option>
						<a-select-option value="CREATIVE_STATUS_DATA_ERROR">数据错误</a-select-option>
						<a-select-option value="CREATIVE_STATUS_PRE_ONLINE">预上线</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AD_AUDIT">广告计划新建审核中</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AD_REAUDIT">广告计划修改审核中</a-select-option>
						<a-select-option value="CREATIVE_STATUS_AD_AUDIT_DENY">广告计划审核不通过</a-select-option>
						<a-select-option value="CREATIVE_STATUS_ALL">所有包含已删除</a-select-option>
						<a-select-option value="CREATIVE_STATUS_NOT_DELETE">所有不包含已删除</a-select-option>
						<a-select-option value="CREATIVE_STATUS_ADVERTISER_BUDGET_EXCEED">超出账户日预算</a-select-option>
					</a-select>
					</a-form-item>
				</a-col>
				<a-col :md="8" :sm="24" >
					<a-form-item
					label="关键词搜索"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-input v-decorator="[
					'creative_title',
					]"
				placeholder="请输入名称或ID搜索" />
					</a-form-item>
				</a-col>
				<a-col :md="8" :sm="24" >
				<a-form-item
					label="素材样式"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-select  v-decorator="[
					'image_mode',
					]" placeholder="请选择" :allowClear="true">
						<a-select-option value="CREATIVE_IMAGE_MODE_SMALL">小图</a-select-option>
						<a-select-option value="CREATIVE_IMAGE_MODE_LARGE">大图横图</a-select-option>
						<a-select-option value="CREATIVE_IMAGE_MODE_VIDEO">横版视频</a-select-option>
						<a-select-option value="CREATIVE_IMAGE_MODE_LARGE_VERTICAL">大图竖图</a-select-option>
						<a-select-option value="CREATIVE_IMAGE_MODE_VIDEO_VERTICAL">竖版视频</a-select-option>
					</a-select>
					</a-form-item>
					
				</a-col>
				</a-row>
				<a-row v-if="advanced">

				<a-col :md="8" :sm="24" >
					<a-form-item
					label="创意方式"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-select  v-decorator="[
					'pricing',
					]" placeholder="请选择" :allowClear="true">
						<a-select-option value="PRICING_CPC">CPC</a-select-option>
						<a-select-option value="PRICING_CPM">CPM</a-select-option>
						<a-select-option value="PRICING_OCPM">OCPM</a-select-option>
						<a-select-option value="PRICING_CPV">CPV</a-select-option>
						<a-select-option value="PRICING_CPA">CPA</a-select-option>
					</a-select>
					</a-form-item>
				</a-col>

				<a-col :md="8" :sm="24" >
					<a-form-item
					label="推广目的"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-select  v-decorator="[
					'landing_type',
					]" placeholder="请选择" :allowClear="true">
						<a-select-option value="LINK">销售线索收集</a-select-option>
						<a-select-option value="APP">应用推广</a-select-option>
						<a-select-option value="DPA">商品目录推广</a-select-option>
						<a-select-option value="GOODS">商品推广（鲁班）</a-select-option>
						<a-select-option value="STORE">门店推广</a-select-option>
						<a-select-option value="AWEME">抖音号推广</a-select-option>
						<a-select-option value="SHOP">电商店铺推广</a-select-option>
						<a-select-option value="ARTICAL">头条文章推广</a-select-option>
					</a-select>
					</a-form-item>
				</a-col>

				<a-col :md="8" :sm="24" >
					<a-form-item
					label="投放账户"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
					<a-select v-decorator="[
						'account_id',
						 {rules:[],initialValue:account_id}
						]" placeholder="请选择投放账户" :value="account_id" :allowClear="true">
						<a-select-option v-for="(item,index) in datalist" :key="index" :value="item.account_id">{{item.account_id}}({{item.name}})</a-select-option>
					</a-select>
					</a-form-item>
				</a-col>

				<a-col :md="8" :sm="24" >
					<a-form-item
					label="统计时间范围"
					:labelCol="{span: 5}"
					:wrapperCol="{span: 18, offset: 1}"
					>
						<a-range-picker v-decorator="[
						'creative_create_time',
						]" 
						:disabled-date="disabledDate"
						 />
					</a-form-item>
					
				</a-col>

				</a-row>
				</div>
				<span style="float: right; margin-top: 3px;">
				<a-button type="primary" @click="queryresult">查询</a-button>
				<a-button @click="btncancel" style="margin-left: 8px">重置</a-button>
				<a @click="toggleAdvanced" style="margin-left: 8px">
					{{advanced ? '收起' : '展开'}}
					<a-icon :type="advanced ? 'up' : 'down'" />
				</a>
				</span>
			</a-form>
			</div>
			<div>
			<div class="operator">
				<a-button @click="addNew" type="primary">新建</a-button>
				<!-- <a-button >批量操作</a-button> -->
				<a-dropdown>
				<a-menu @click="handleMenuClick" slot="overlay">
					<a-menu-item key="delete">启用</a-menu-item>
					<a-menu-item key="audit">暂停</a-menu-item>
					<a-menu-item key="audit">删除</a-menu-item>
				</a-menu>
				</a-dropdown>
				<a-button @click="synction"><a-icon type="sync" />同步</a-button>
			</div>

			  <a-modal
				title="选择同步广告投放账号"
				:visible="visible"
				:confirm-loading="confirmLoading"
				@ok="handleOk"
				@cancel="handleCancel"
				:width="700"
			>
				<p>说明:同步时间与数量相关,确认后将自动同步,请耐心等待</p>
				<a-input-search placeholder="请输入名称或ID搜索" style="width: 200px;margin-bottom:16px;" @search="onSearch" />

				<a-table :row-selection="rowacountlist" :columns="acountlabel" :scroll="{ x: 210, y: 500 }" :pagination="false" :data-source="datalist">
					<a slot="name" slot-scope="text">{{ text.name }}</a>
				</a-table>
			
			</a-modal>

			<a-table
				:columns="columns"
				:dataSource="dataSource.list"
				:selectedRows.sync="selectedRows"
				@clear="onClear"
				@change="handleTableChange"
				@selectedRowChange="onSelectChange"
				:pagination="paginationOpt"
				:loading='tableloading'
				:row-selection="rowSelection"
				:scroll="{ x: 1500 }"
			>
			<div slot="switchDemo" slot-scope="text">
				<a-switch :defaultChecked="text.status =='CAMPAIGN_STATUS_ENABLE' ? true : false" @change="onChangedata(text.id)" />
			</div>

				<!-- 广告主 -->
				<div slot="mainDemo" slot-scope="text">
					<span>
						{{text.account_id}}
						<p>{{text.ocean_account.name}}</p>
					</span>
				</div>

			<!-- 创意素材类型 -->
				<div slot="modeDemo" slot-scope="text">
				<span v-if="text =='CREATIVE_IMAGE_MODE_SMALL'">小图</span>
				<span v-else-if="text == 'CREATIVE_IMAGE_MODE_LARGE'">大图横图</span>
				<span v-else-if="text == 'CREATIVE_IMAGE_MODE_VIDEO'">横版视频</span>
				<span v-else-if="text == 'CREATIVE_IMAGE_MODE_LARGE_VERTICAL'">大图竖图</span>
				<span v-else-if="text == 'CREATIVE_IMAGE_MODE_VIDEO_VERTICAL'">竖版视频</span>
				<span v-else>默认</span>
				</div>


		<!-- 创意素材操作状态 -->
				<div slot="optStatus" slot-scope="text">
				<span v-if="text =='CREATIVE_STATUS_ENABLE	'">启用</span>
				<span v-else-if="text == 'CREATIVE_STATUS_DISABLE'">暂停</span>
				<span v-else-if="text == 'CREATIVE_STATUS_DELETE'">删除</span>
				<span v-else-if="text == 'LANDING_PAGE_LINK'">落地页</span>
				<span v-else>--</span>
				</div>

			<!-- 状态 -->
				<div slot="statusDemo" slot-scope="text">
				<span v-if="text =='CREATIVE_STATUS_DELIVERY_OK'">投放中</span>
				<span v-else-if="text == 'CREATIVE_STATUS_NOT_START'">未到达投放时间</span>
				<span v-else-if="text == 'CREATIVE_STATUS_NO_SCHEDULE'">不在投放时段</span>
				<span v-else-if="text == 'CREATIVE_STATUS_DISABLE'">创意暂停</span>
				<span v-else-if="text == 'CREATIVE_STATUS_CAMPAIGN_DISABLE'">已被广告组暂停</span>
				<span v-else-if="text == 'CREATIVE_STATUS_CAMPAIGN_EXCEED'">广告组超出预算</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AUDIT'">新建审核中</span>
					<span v-else-if="text == 'CREATIVE_STATUS_REAUDIT'">修改审核中</span>
					<span v-else-if="text == 'CREATIVE_STATUS_DELETE'">已删除</span>
					<span v-else-if="text == 'CREATIVE_STATUS_DONE'">已完成</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AD_DISABLE'">广告计划暂停</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AUDIT_DENY'">审核不通过</span>
					<span v-else-if="text == 'CREATIVE_STATUS_BALANCE_EXCEED'">账户余额不足</span>
					<span v-else-if="text == 'CREATIVE_STATUS_BUDGET_EXCEED'">超出预算</span>
					<span v-else-if="text == 'CREATIVE_STATUS_DATA_ERROR'">数据错误</span>
					<span v-else-if="text == 'CREATIVE_STATUS_PRE_ONLINE'">预上线</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AD_AUDIT'">广告计划新建审核中</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AD_REAUDIT'">广告计划修改审核中</span>
					<span v-else-if="text == 'CREATIVE_STATUS_AD_AUDIT_DENY'">广告计划审核不通过</span>
					<span v-else-if="text == 'CREATIVE_STATUS_ALL'">所有包含已删除</span>
					<span v-else-if="text == 'CREATIVE_STATUS_NOT_DELETE'">所有不包含已删除</span>
					<span v-else-if="text == 'CREATIVE_STATUS_ADVERTISER_BUDGET_EXCEED'">超出账户日预算</span>
				<span v-else>不限</span>
				</div>


			<div slot="action" slot-scope="text">
				<a style="margin-right: 8px" @click="tolink(text)">
					<a-icon type="edit"/>编辑
				</a>
				<!-- <a @click="deleteRecord(record.key)">
					<a-icon type="book" />预览
				</a> -->
				</div>
			</a-table>

			</div>
		</a-card>
	</div>
</div>
</template>

<script>
import {CREATIVE,ACCOUNTURL,SYNCURL} from '@/services/api'
import {ajaxparems} from '@/services/ajaxrequest'
import moment from 'moment';
const columns = [
  	{
		title: '',
		width: 60,
		fixed:'left',
		scopedSlots: { customRender: 'switchDemo' }
	},
	{
		title: '广告主',
		width:160,
		fixed:'left',
		scopedSlots: { customRender: 'mainDemo' }
	},
	{
		title: '广告创意',
		width:160,
		fixed:'left',
		dataIndex: 'title'
	},
  {
	title: '广告创意状态',
	width:130,
    dataIndex: 'status',
    scopedSlots: { customRender: 'statusDemo' }
  },
  {
	  title: '计划ID',
	  width:220,
      dataIndex: 'ad_id'
  },
//   {
// 	title: '广告组名称',
// 	width:130,
//     dataIndex: 'advertiser_id'
//   },
//   {
// 	title: '创意素材状态',
// 	width:130,
//     dataIndex: 'opt_status',
//     scopedSlots: { customRender: 'optStatus' }
//   },
  {
	title: '创意素材类型',
	width:130,
    dataIndex: 'image_mode',
    scopedSlots: { customRender: 'modeDemo' }
  },
  {
	title: '消耗',
	width:130,
	sorter: (a, b) => a.cost - b.cost,
    dataIndex: 'cost'
  },
  {
	title: '点击数',
	width:130,
	sorter: (a, b) => a.click - b.click,
    dataIndex: 'click'
  },
    {
	title: '展示数',
	width:130,
	sorter: (a, b) => a.show - b.show,
    dataIndex: 'show'
  }, {
	title: '转化数',
	width:130,
	sorter: (a, b) => a.convert - b.convert,
    dataIndex: 'convert'
  },{
	title: '千次展示成本',
	width:130,
	sorter: (a, b) => a.show_cost - b.show_cost,
    dataIndex: 'show_cost'
  },{
	title: '点击成本',
	width:130,
	sorter: (a, b) => a.click_cost - b.click_cost,
    dataIndex: 'click_cost'
  },
  {
	title: '点击率',
	width:130,
	sorter: (a, b) => a.click_rate - b.click_rate,
    dataIndex: 'click_rate'
  },
  {
	title: '转化成本',
	width:130,
	sorter: (a, b) => a.convert_cost - b.convert_cost,
    dataIndex: 'convert_cost'
  },
   {
	title: '转化率',
	width:130,
	sorter: (a, b) => a.convert_rate - b.convert_rate,
    dataIndex: 'convert_rate'
  },
   {
	title: '操作',
	width:100,
	fixed:'right',
    scopedSlots: { customRender: 'action' }
  },
]
var acountlabel = [
	{
		title:'广告账号',
		scopedSlots: { customRender: 'name' }
	}
]
var dataSource = [];
var datalist =[];
export default {
  name: 'OriginaList',
  // components: {StandardTable},
   created(){
      var account_id = this.$route.query.account_id;
      this.account_id = account_id;
		this.listNew();
		this.accountlist();
	},
	beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  data () {
    return {
		spinning:true,
      account_id:'',
      advanced: false,
      columns: columns,
      dataSource:dataSource,
      selectedRows: [],
		checkaccount:[],
		spinnings:false,

		visible:false,
		acountlabel,
		datalist,
		tableloading:true,

	  paginationOpt: {
		defaultCurrent: 1, // 默认当前页数
		defaultPageSize: 10, // 默认当前页显示数据的大小
		total: 0, // 总数，必须先有
		showSizeChanger: true,
		showQuickJumper: true,
		pageSizeOptions: ["5", "10", "15", "20"],
		showTotal: (total) => `共 ${total} 条`, // 显示总数
		onShowSizeChange: (current, pageSize) => {
			this.paginationOpt.defaultCurrent = 1;
			this.paginationOpt.defaultPageSize = pageSize;
			this.listNew(); //显示列表的接口名称
		},
		// 改变每页数量时更新显示
		onChange: (current, size) => {
			this.paginationOpt.defaultCurrent = current;
			this.paginationOpt.defaultPageSize = size;
			this.listNew();
		},
	},
    }
  },
  authorize: {
    deleteRecord: 'delete'
  },
  methods: {
	  moment,
	   disabledDate(current) {
			//  return time.getTime() > Date.now();
			// return current && current >=moment().subtract(1, "days");
			return current && current >= moment().endOf('day');
		},
	  synction(){
			//同步
			this.visible = true;
		},
		handleCancel(){
			// 取消同步
			this.visible = false;
		},
		onSearch(e){
			// 同步账号搜索
			var parems = {"filtering":[
				{"field":'name',"operator":'LIKE',"value":e},
			]};
			ajaxparems(ACCOUNTURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					this.datalist =result.data;
					// this.reload();
				}else{
 					this.$message.error(result.message, 3)
				}
			})
		},
		handleOk(){
			// 确定同步
			if(this.checkaccount.length <=0){
				this.$message.error("请选择同步账号");
				return;
			}
			var accountlist = [];
			this.checkaccount.forEach((res)=>{
				accountlist.push(res.account_id);
			})
			var parems = {"account_ids":accountlist,"type":'CREATIVE'}
			ajaxparems(SYNCURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					this.visible = false;
					this.$message.success(result.message,3);
					this.reload();
				}else{
					this.visible = false;
					this.$message.error(result.message, 3)
				}
			})
		},

    tolink(e){
      this.$router.push({
          path: '/promotion/advering/editorigin/',
          query: {
              ad_id: e.ad_id,//计划ID
              advertiser_id:e.advertiser_id,//广告主ID
              creative_id:e.creative_id//创意id
          }
      })
    },
    deleteRecord(key) {
      this.dataSource = this.dataSource.filter(item => item.key !== key)
      this.selectedRows = this.selectedRows.filter(item => item.key !== key)
  },
   btncancel(){
    //   重置
       this.form.resetFields();
  },
	queryresult(){
		this.paginationOpt.defaultCurrent = 1;
		this.paginationOpt.defaultPageSize = 10;
		this.listNew();
	},
	handleSubmit(res){
		console.log(res);
	},
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    remove () {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onStatusTitleClick() {
      this.$message.info('你点击了状态栏表头')
    },
   handleTableChange(pagination, filters, sorter) {
		console.log('params', pagination, filters, sorter);
	},
    onSelectChange() {
      this.$message.info('选中行改变了')
    },
    addNew () {
		this.$router.push('/promotion/advering/chooseaplan')
	},
	accountlist(){
		// 获取广告主账号
		ajaxparems(ACCOUNTURL,"").then((res) => {
			var result=res.data;
			if(result.code =="SUCCESS"){
				this.datalist =result.data;
			}else{
				this.$message.error(result.message, 3)
			}
		})
	},

	listNew() {
	// 获取创意列表
		this.tableloading = true;
			const { defaultCurrent, defaultPageSize } = this.paginationOpt;
			this.form.validateFieldsAndScroll((err, values) => {
				var parems = {};
				var paremsinfo = [];
				var time = '';
				var times = '';
				if(values['status'] !=undefined){
					if(values['status'] =="CREATIVE_STATUS_ALL"){
						// paremsinfo.push({"field":"status","operator":"IN","value":['CAMPAIGN_STATUS_DELETE']})
					}else if(values['status'] =='CAMPAIGN_STATUS_NOT_DELETE'){
						paremsinfo.push({"field":"status","operator":"NOT_IN","value":['CREATIVE_STATUS_DELETE']})
					}else{
						paremsinfo.push({"field":"status","operator":"EQUALS","value":values['status']})
					}
				}
				if(values['creative_title'] !=undefined && values['creative_title'] !=''){
					var numReg = /^[0-9]*$/
					var numRe = new RegExp(numReg)
					if (!numRe.test(values['creative_title'])) {
						paremsinfo.push({"field":"name","operator":"LIKE","value":values['creative_title']})
					}else{
						paremsinfo.push({"field":"id","operator":"LIKE","value":values['creative_title']})
					}
				}

				if(values['image_mode'] !=undefined){
					paremsinfo.push({"field":"image_mode","operator":"EQUALS","value":values['image_mode']})
				}

				if(values['pricing'] !=undefined){
					paremsinfo.push({"field":"image_mode","operator":"EQUALS","value":values['image_mode']})
				}

				if(values['landing_type'] !=undefined){
					paremsinfo.push({"field":"landing_type","operator":"EQUALS","value":values['landing_type']})
				}
				if(values['account_id'] !=undefined){
					paremsinfo.push({"field":"account_id","operator":"EQUALS","value":values['account_id']})
				}

				if(values['creative_create_time'] !=undefined && values['creative_create_time'] !=''){
					time = moment(values['creative_create_time'][0]).format('YYYY-MM-DD')
					times = moment(values['creative_create_time'][1]).format('YYYY-MM-DD')
				}
				if(paremsinfo.length >0){
					parems = {
						page:defaultCurrent,
						page_size:defaultPageSize,
						start_date:time,
						end_date:times,
						"filtering":paremsinfo
					};
				}else{
					parems ={
						page:defaultCurrent,
						page_size:defaultPageSize,
						start_date:time,
						end_date:times,
						"filtering":[
						{"field":"status","operator":"NOT_IN","value":["CREATIVE_STATUS_DELETE"]}//不包含已删除
					]}
				}

				if(time =='' || times ==''){
					this.$delete(parems,'start_date');
					this.$delete(parems,'end_date');
				}

				// 获取默认广告组
				ajaxparems(CREATIVE,parems).then((res) => {
					var result=res.data;
					if(result.code =="SUCCESS"){
						result.data.list.map(v=>{
							v.switchloading = false				
						});
						this.paginationOpt.total = result.data.page_info.total;
						this.dataSource = result.data;
						this.tableloading = false;
					}else{
						this.tableloading = false;
						this.$message.error(result.message, 3)
					}
				})
			})
	
		this.spinning = false;
	},
    handleMenuClick (e) {
      if (e.key === 'delete') {
        this.remove()
      }
    }
  },computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
			    this.selectedRows = selectedRows;
        //   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
      };
    },
	rowacountlist() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
		//   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
			this.checkaccount = selectedRows;
        },
      };
    }
  }
}
</script>

<style lang="less" scoped>
  .search{
    margin-bottom: 54px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
